package com.lastproject.ejb.util;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.BookDTO;
import com.lastproject.ejb.entities.Book;
import com.lastproject.ejb.entities.Domain;

/**
 * Session Bean implementation class BookConversion
 */
@Stateless
@LocalBean
public class BookConversion {

	@PersistenceContext
	EntityManager entityManager;

	/**
	 * Default constructor.
	 */
	public BookConversion() {
		// TODO Auto-generated constructor stub
	}

	public BookDTO fromEntity(Book book) {
		BookDTO bookDTO = new BookDTO();
		bookDTO.setAuthor(book.getAuthor());
		bookDTO.setIdDomain(book.getDomain().getId());
		bookDTO.setYear(book.getYear());
		bookDTO.setId(book.getId());
		bookDTO.setName(book.getName());
		bookDTO.setStatus(book.getStatus());

		return bookDTO;
	}

	public Book fromDTO(BookDTO bookDTO) {
		Book book = entityManager.find(Book.class, bookDTO.getId());

		if (book == null) {
			book = new Book();
		}
		Domain domain = entityManager.find(Domain.class, bookDTO.getIdDomain());
		book.setDomain(domain);
		book.setAuthor(bookDTO.getAuthor());
		book.setYear(bookDTO.getYear());
		book.setName(bookDTO.getName());
		book.setStatus(bookDTO.getStatus());

		return book;
	}
}
